package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.common.PageParam;
import com.itheima.dao.EmployeeDao;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;


    /**
     * 登录： 使用账号和密码来查询员工信息！
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {

        //1. 构建条件对象
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        //2. 设置条件
        qw.eq(Employee::getUsername , employee.getUsername());

        //2.1 对密码进行加密，使用密文去匹配数据库的数据
        String pwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        qw.eq(Employee::getPassword ,pwd );

        //3. 执行查询
        return employeeDao.selectOne(qw);
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @Override
    public int add(Employee employee) {
        return employeeDao.insert(employee);
    }

    /**
     * 更新员工
     * @param employee
     * @return
     */
    @Override
    public int update(Employee employee) {
        return employeeDao.updateById(employee);
    }

    /**
     * 员工分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Employee> findPage(PageParam pageParam) {

        //1. 构建IPage对象 ,设置查询第几页，每页查询多少条
        IPage<Employee> p = new Page<>(pageParam.getPage() , pageParam.getPageSize());

        //2. 分页操作，有可能附带查询条件，所以需要准备查询条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        //2.1 设置条件，按照姓名来查询用户，顺便分页。
        qw.like( pageParam.getName() != null ,Employee::getName , pageParam.getName());

        //3. 查询分页
        return  employeeDao.selectPage(p, qw);
    }
}
